<template>
  <div class="login-container">
    <div class="login-form">
      <div class="logo-area">
        <el-avatar size="80" icon="el-icon-office-building" :style="{backgroundColor: '#409eff'}"></el-avatar>
        <h2>单点登录系统</h2>
      </div>
      
      <el-form :model="form" :rules="rules" ref="formRef" label-width="0">
        <el-form-item prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名" 
            prefix-icon="el-icon-user-solid"
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="form.remember" class="remember-checkbox">记住密码</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            class="login-btn"
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="tip-text">
        <el-tag size="small" type="info">测试账号: user1 / 123456</el-tag>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../utils/axios'
import { ElMessage } from 'element-plus'
import { getRedirectUrl, buildLoginParams, handleLoginRedirect } from '../utils/ssoUtils.js'

const router = useRouter()
const formRef = ref()
const loading = ref(false)
const form = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ]
}

// 检查是否有记住的密码
const checkRemembered = () => {
  const savedUsername = localStorage.getItem('rememberedUsername')
  const savedPassword = localStorage.getItem('rememberedPassword')
  if (savedUsername && savedPassword) {
    form.username = savedUsername
    form.password = savedPassword
    form.remember = true
  }
}

// 处理登录逻辑
const handleLogin = async () => {
  // 表单验证
  await formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.warning('请填写正确的登录信息')
      return false
    }
    
    // 模拟登录加载
    loading.value = true
    
    try {
      // 获取回调地址
      const redirectUrl = getRedirectUrl()
      
      // 构建登录请求参数（会自动进行SM3+SM4双重加密）
      const loginParams = buildLoginParams(form.username, form.password, redirectUrl)
      
      // 调用SSO登录接口
      api.ssoLogin(loginParams)
        .then(response => {
          if (!response.code || response.code !== 200) {
            ElMessage.error(response.message || '登录失败')
            return
          }
          // 假设后端返回的数据格式包含token和用户信息
          const { token, userInfo } = response.data || {};
          
          // 存储token和用户信息
          if (token) {
            // localStorage.setItem('token', token)
          }
          
          if (userInfo) {
            localStorage.setItem('currentUser', JSON.stringify(userInfo))
          }
          
          // 如果记住密码
          if (form.remember) {
            localStorage.setItem('rememberedUsername', form.username)
            localStorage.setItem('rememberedPassword', form.password)
          } else {
            localStorage.removeItem('rememberedUsername')
            localStorage.removeItem('rememberedPassword')
          }
          
          ElMessage.success('登录成功')
          
          // 处理跳转
          handleLoginRedirect(redirectUrl)
        })
        .catch(error => {
          console.error('登录失败:', error)
          ElMessage.error(error.response?.data?.message || '用户名或密码错误')
        })
        .finally(() => {
          loading.value = false
        })
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请重试')
      loading.value = false
    }
  })
}

// 组件挂载时检查URL参数和记住密码
onMounted(() => {
  checkRemembered()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 400px;
  animation: fadeInUp 0.5s ease-out;
}

.logo-area {
  text-align: center;
  margin-bottom: 30px;
}

.logo-area h2 {
  margin-top: 15px;
  color: #303133;
  font-size: 22px;
}

.login-btn {
  height: 40px;
  font-size: 16px;
  margin-top: 10px;
}

.remember-checkbox {
  font-size: 14px;
}

.tip-text {
  text-align: center;
  margin-top: 20px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-form {
    padding: 25px;
  }
}
</style>